package com.yudaxian.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yudaxian.common.HoneyLogs;
import com.yudaxian.common.enums.LogType;
import com.yudaxian.common.vo.Result;
import com.yudaxian.sys.entity.Role;
import com.yudaxian.sys.service.IRoleService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yudaxian
 * @since 2023-09-21
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private IRoleService roleService;

    @GetMapping("/all")
    public Result<List<Role>> getAllRoles() {
        List<Role> roles = roleService.list();
        return Result.success(roles);
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getRoleList(
            @RequestParam(value = "roleName", required = false) String roleName,
            @RequestParam(value = "pageNo") Integer pageNo,
            @RequestParam(value = "pageSize") Integer pageSize) {

        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(roleName), Role::getRoleName, roleName);

        Page<Role> page = new Page<>(pageNo, pageSize);
        roleService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @HoneyLogs(operation = "角色", type = LogType.ADD)
    @PostMapping("/add")
    //RequestBody，json转role对象，前端输入数据，传给后台json，再转成对象，存入数据库
    public Result<?> addRole(@RequestBody Role role) {
        roleService.addRole(role);
        return Result.success("新增角色成功");
    }

    @HoneyLogs(operation = "角色", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result<?> updateRole(@RequestBody Role role) {
        roleService.updateRole(role);
        return Result.success("修改成功");
    }

    @GetMapping("{id}")
    public Result<Role> getRoleById(@PathVariable("id") Integer id) {
        Role role = roleService.getRoleById(id);

        return Result.success(role);
    }

    @HoneyLogs(operation = "角色", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteRoleById(@PathVariable("id") Integer id) {
        roleService.deleteRoleById(id);

        return Result.success("删除成功");
    }

}
